package com.kylin.module.community.actions;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import java.util.List;
import java.util.Locale;

//import java.util.ResourceBundle;

//import java.util.Locale;
//import com.kylin.common.util.ShortResourceBundle;

import com.kylin.common.paginate.Paging;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

import com.kylin.common.Constants;

import com.kylin.module.user.orm.User;
import com.kylin.hibernate.BaseHibernateDAO;
//import com.kylin.module.admin.form.CatDictForm;
import com.kylin.module.community.business.PostBlogic;

import com.kylin.module.community.orm.Post;

import com.kylin.module.community.forms.PostForm;

import com.kylin.struts.BaseDispatchAction;

import com.kylin.common.dict.orm.Dict;
import com.kylin.common.exception.BusinessException;
import com.kylin.common.util.MemObjFactory;

import com.kylin.module.shop.orm.Company;

public class PostAction  extends BaseDispatchAction {

	protected static Logger log = Logger.getLogger(MemberAction.class);	
	
	public ActionForward unspecified(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		return null;
	}
	
	public ActionForward redirect(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		User user = null;
		String forwardto = null;
		log.debug("redirect, vendor:" + request.getParameter("vendor"));
		try {
			if(request.getParameter("uid") != null ){
				  user = (User)BaseHibernateDAO.findById(User.class, new Long(request.getParameter("uid")));
			}		
		}
		catch (Exception e) {
			e.printStackTrace();
			
		}
		
		if (user != null){				
				if(user.getUserrole().equals(Constants.USER_ROLE_COMPANY) ){
					log.debug("subs:"+user.getSubs());
					if ( user.getSubs() != null){
						//log.info("===================================" + getSessionLocale(request).toString());
						Company curr_company = null;
						try{						
								Company[] user_companys = (Company[])user.getSubs().toArray(new Company[0]);								
								curr_company = (Company)user_companys[0];							
							    for(int i=0;i<user_companys.length;i++){
							    	if(user_companys[i].getLanguage().equals(getSessionLocale(request).toString()) ) 
									    curr_company = user_companys[i];
							    }	
						}
						catch(Exception e){								
								e.printStackTrace();						
						}
					    if (request.getParameter("vendor")==null){
					    	forwardto = "/module/shop/company/shop.do?CMD=companyShopList&companyId=" + curr_company.getId().toString();
					    }
					    else{
					    	forwardto = "/module/shop/company/manage1.jsp";
					    }
					}else{
						forwardto ="/module/shop/company/manage1.jsp";
					}					
				}else{
					forwardto = "/module/community/member/post.do?task=mypost&uid="+request.getParameter("uid");
				}
		}
		//log.info(">>>>>>>>>>>>>>>>>> forwardto:" + forwardto);
		ActionForward actionforward = new ActionForward(forwardto);
		actionforward.setRedirect(true);
		return actionforward;	
		
	}	
	public ActionForward show(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		
		Locale loc = (Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
		log.info("locale: "+loc);
		String forward = "show";
		log.info("in post.show : " + forward); 	
		PostForm postform = (PostForm)actionForm;
		
		log.info(postform.toString());
		Integer limitstart = new Integer("0");
		Integer limit = new Integer("10");
		if(request.getParameter("limitstart") != null )	{		
			limitstart = new Integer (request.getParameter("limitstart"));
		}	
		if(request.getParameter("limit") != null ){
			limit = new Integer (request.getParameter("limit"));
		}
		User user = null;

		try {
			if(request.getParameter("uid") != null ){
				  user = (User)BaseHibernateDAO.findById(User.class, new Long(request.getParameter("uid")));
			    }
			PostBlogic bean = new PostBlogic();			
			Paging page = bean.show(user, limitstart,limit, postform, loc);	
			//request.setAttribute("uid", uid);	
			request.setAttribute("posts", page);			
		
		}catch (Exception e) {
			doException( request, e, forward);
		}
		
		try{
			if (postform.getCatpostid() != null && postform.getCatpostid().intValue() != 0 ){
				Dict catpost= (Dict)BaseHibernateDAO.findById(Dict.class, postform.getCatpostid());
				request.setAttribute("cat", catpost);
			}
			if (postform.getTagid() != null && postform.getTagid().intValue() != 0 ){
				Dict tag= (Dict)BaseHibernateDAO.findById(Dict.class, postform.getTagid());
				request.setAttribute("tag", tag);
			}			
		}
		catch(BusinessException be){
			
		}
		if("ok".equals(request.getParameter("msg"))){
			log.info(">>>>>>>>>>>>got ok");
			Locale locale = getSessionLocale(request);//(Locale) session.getAttribute(Action.LOCALE_KEY);
			ActionMessages messages = new ActionMessages();
			messages.add("msg", new ActionMessage("好友添加成功"));
			saveMessages(request, messages);
			
		}else{
			log.info(">>>>>>>did not get ok");
		}
		
		request.setAttribute("postform", postform);	
		return mapping.findForward(forward);
	}	
	
	public ActionForward mypost(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		
		String forward = "mypost";
		log.info("in post.show : " + forward);
		
		Long uid = null;
		if(request.getParameter("uid") != null){
			uid = new Long (request.getParameter("uid"));
		}		
		
		Integer limitstart = new Integer("0");
		Integer limit = new Integer("10");
		if(request.getParameter("limitstart") != null )	{		
			limitstart = new Integer (request.getParameter("limitstart"));
		}	
		if(request.getParameter("limit") != null ){
			limit = new Integer (request.getParameter("limit"));
		}
		User user = null;
		if (uid == null || uid.intValue() == 0){
			  if(request.getSession().getAttribute(Constants.CURR_USER)!= null){
				  user = (User)request.getSession().getAttribute(Constants.CURR_USER);
				  uid = user.getId();
				  
			  }
			  else{
				  return mapping.findForward("login");
			  }
		}
		else{
			try{
			user = (User)BaseHibernateDAO.findById(User.class, uid);
			}
			catch(BusinessException e){
				doException( request, e, forward);
			}
			
		}
		
		try {

			PostBlogic bean = new PostBlogic();			
			Locale loc = (Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
			Paging page = bean.show(user, limitstart, limit, null, null);
			log.info("pagesize: " + page.getList().size());
			request.setAttribute("cuser", user);
			request.setAttribute("uid", uid);	
			request.setAttribute("posts", page);			
		
		}catch (Exception e) {
			doException( request, e, forward);
		}
		
		if("ok".equals(request.getParameter("msg"))){
			log.info(">>>>>>>>>>>>got ok");
			Locale locale = getSessionLocale(request);//(Locale) session.getAttribute(Action.LOCALE_KEY);
			ActionMessages messages = new ActionMessages();
			messages.add("msg", new ActionMessage("好友添加成功"));
			saveMessages(request, messages);
			
		}else{
			log.info(">>>>>>>do not got ok");
		}		
		
		return mapping.findForward(forward);
	}	

	public ActionForward save(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.save");
		String forward = "view";
		PostForm postform = (PostForm) actionForm;
		log.info(postform.toString());
		String message = request.getParameter("message");
		User user = (User)request.getSession().getAttribute(Constants.CURR_USER);
		Locale loc = (Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
		Post post = null;
		if (user == null){
			log.info("no user session");
			forward = "login";
		}else{		
		
			String user2id = request.getParameter("uid");
		
			try{
				PostBlogic bean = new PostBlogic();
				
				post = bean.save(user, postform, loc); //parent post id = 0 here
				
				
				log.info("保存 message：");
			}catch (Exception e) {
				forward = doException( request, e, forward);
			}
		}
		
		String forwardto = null;
		if (post != null){
			forwardto = "/module/community/post/post.do?task=view&pid="+post.getId().toString();
		}
		else{
			forwardto = "/module/community/post/post.do?task=view&pid=1";			
		}
		ActionForward actionforward = new ActionForward(forwardto);
		actionforward.setRedirect(true);
		return actionforward;			
		//log.info("forward to " + forward);
		//return mapping.findForward(forward);
	}

	public ActionForward search(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		// TODO Auto-generated method stub
		return null;
	}	

	public ActionForward add(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.add");
		String forward = "add";
		String pid = request.getParameter("pid");
		
		log.info("user language: " + request.getSession().getAttribute(Constants.USER_ACCEPTLANGUAGE));
		
		if (request.getSession().getAttribute(Constants.CURR_USER)== null){
			
			forward = "login";
			request.setAttribute("forward", "post.add");
		}else{		
			Locale locale = getSessionLocale(request);//new Locale("zh","CN");
			//String language = locale.toString();
			//language = "zh_CN";
			//List list = bean.findByLanguage(language);
			List tags = null;
			List post = null;
			try{
			  tags = MemObjFactory.getDict("tags", locale.toString());
			  post = MemObjFactory.getDict("post", locale.toString());			
			}
			catch(Exception e){
				log.info(e.toString());
			}
			
			if (pid != null){
			PostBlogic bean = new PostBlogic();
			
			Post p = (Post)bean.findById(new Long(pid));
			request.setAttribute("onepost", p);
			}
			
			request.setAttribute("fkppostid", pid);		
			request.setAttribute("tags", tags);
			request.setAttribute("post", post);			
		}
		return mapping.findForward(forward);
	
	}	
	
	public ActionForward delete(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.delete");
		String forward = "show";
		if (request.getSession().getAttribute(Constants.CURR_USER)== null){
			
			forward = "login";
			request.setAttribute("forward", "post.add");
			return mapping.findForward(forward);
		}
		else{
			User user = (User)request.getSession().getAttribute(Constants.CURR_USER);
			Long pid = new Long(request.getParameter("pid"));
			PostBlogic bean = new PostBlogic();
			bean.deleteById(pid);		
			String path = "/module/community/member/post.do?task=mypost&uid="+ user.getId();
			log.info("path: "+path);
	
			ActionForward actionforward = new ActionForward(path);
			actionforward.setRedirect(true);
			return actionforward;
		}
		//return mapping.findForward(forward);
	}

	public ActionForward last(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.last : searchId="+request.getParameter("searchId"));
		String forward = "last";
		try {

			PostBlogic bean = new PostBlogic();
			Locale loc = (Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
			List list = bean.getLastPost(loc);
			//list.get(index)
			
			List tags = null;
			Locale locale = getSessionLocale(request);// new Locale("zh","CN");
			//String language = locale.getLanguage();
			//language = "zh_CN";				 
			try{
			  tags = MemObjFactory.getDict("tags", locale.toString());
			}
			catch(Exception e){
				log.info(e.toString());
			}
			request.setAttribute("tags", tags);			
			request.setAttribute("lastposts", list);	
			
		}catch (Exception e) {
			doException( request, e, "search");
		}
		return mapping.findForward(forward);
	}

	public ActionForward info(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.info");
		Long uid = new Long(request.getParameter("uid"));
		String forward = "list";
		try {

			PostBlogic bean = new PostBlogic();
			
			//User user = (User)request.getSession().getAttribute(Constants.CURR_USER);
			//Long userid = new Long("1");
			//User user = BaseHibernateDAO.			
			//log.info(" userid :"+ user.getId());
			List list = bean.getPostByUserId(uid);
			//list.get(index)
			log.info("size :"+ list.size());
			//request.setAttribute("uid", uid);		
			request.setAttribute("myposts", list);

			
		}catch (Exception e) {
			doException( request, e, forward);
		}
		return mapping.findForward(forward);
	}	
	
	public ActionForward list(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.list");
		String forward = "list";
		try {

			PostBlogic bean = new PostBlogic();
			
			User user = (User)request.getSession().getAttribute(Constants.CURR_USER);
			//Long userid = new Long("1");
			//User user = BaseHibernateDAO.
			if (user == null){
				forward = "login";
			}else{
				
				log.info(" userid :"+ user.getId());
				List list = bean.getPostByUser(user);
				//list.get(index)
				log.info("size :"+ list.size());
				request.setAttribute("myposts", list);
			}
			
		}catch (Exception e) {
			doException( request, e, forward);
		}
		return mapping.findForward(forward);
	}
		
	public ActionForward edit(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.edit");
		return null;
	}

	public ActionForward home(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.home");
	 
		PostBlogic bean = new PostBlogic();
	
		String forward ="home";
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");
		String language = locale.toString();
		//language = "zh_CN";		
		Locale loc = (Locale)request.getSession().getAttribute(org.apache.struts.Globals.LOCALE_KEY);
		List list = bean.getLastPost(loc);
		List postcat = null;		
		List tags = null;
		 
		try{
		  tags = MemObjFactory.getDict("tags", language);
		  postcat = MemObjFactory.getDict("post", language);			
		}
		catch(Exception e){
			log.info(e.toString());
		}
		request.setAttribute("tags", tags);		
		request.setAttribute("postcat", postcat);	
		request.setAttribute("lastposts", list);		
	 	return mapping.findForward(forward);
	}

	public ActionForward tags(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.tags");
		String forward ="tags";
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");
		String language = locale.toString();
		//language = "zh_CN";		
		List tags = null;
		 
		try{
		  tags = MemObjFactory.getDict("tags", language);
		}
		catch(Exception e){
			log.info(e.toString());
		}
		request.setAttribute("tags", tags);		
	 	return mapping.findForward(forward);
	}

	public ActionForward cats(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.postcats");
		String forward ="cats";
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");
		String language = locale.toString();
		//language = "zh_CN";		
		List postcats = null;
		 
		try{
		  postcats = MemObjFactory.getDict("post", language);
		}
		catch(Exception e){
			log.info(e.toString());
		}
		
		
		request.setAttribute("postcats", postcats);	
		
		//Locale locale = getSessionLocale(request);//(Locale) session.getAttribute(Action.LOCALE_KEY);
		ActionMessages messages = new ActionMessages();
		messages.add("post.homemsg", new ActionMessage("post.homemsg",locale));
		saveMessages(request, messages);		
		
		
	 	return mapping.findForward(forward);
	}	
	
	public ActionForward query(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.query");
	 
		String forward ="query";
		Locale locale = getSessionLocale(request);//new Locale("zh","CN");		
		String language = locale.toString();
		//language = "zh_CN";		
		List languages = null;		
		List interests = null;
		languages = MemObjFactory.getSysLanguageList(locale);
		request.setAttribute("languages",languages);
		   
		List countryList = MemObjFactory.getAllCountryList(locale);
		request.setAttribute("countrys",countryList);		  
		 
		try{
	    	interests = MemObjFactory.getDict("interest", language);
		}
		catch(Exception e){
			log.info(e.toString());
		}
		request.setAttribute("interests", interests);		
	 	return mapping.findForward(forward);
	}	
	
	public ActionForward view(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response){
		log.info("in post.view");
		Long pid = new Long(request.getParameter("pid"));
		PostBlogic bean = new PostBlogic();
		Post post = bean.findById(pid);
		String forward ="view";		
		request.setAttribute("cat", post.getCatpost());
		request.setAttribute("post", post);
		return mapping.findForward(forward);
	}	
	
	public ActionForward update(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request, HttpServletResponse response) {
		log.info("in post.update");
		// TODO Auto-generated method stub
		String forward = "list.do";
		log.info("forward :"+forward );
		log.info("forward id:"+((PostForm)actionForm).getId());
		//log.info("查询属性表 :"+ ((MemberForm)actionForm).toString() );
		PostBlogic bean = new PostBlogic();	
		try{
			//bean.updatePost((PostForm)actionForm);
		}catch (Exception e) {
			log.info("forward exception:"+e.toString() );
			forward = doException( request, e, "update");
		}
		
		return mapping.findForward(forward);
	}

}
